package com.tools.utils;

import com.tools.constants.Constant;
import com.tools.entity.GeneratorContent;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 创建文件的 的工具
 *
 * @author < a href=" ">ZhangYang</ a>
 * @version v1.0.01
 * @date 2018-08-01 14:23:26
 */

public class CreateFileUtil {
  private static final Logger LOG = Logger.getLogger(CreateFileUtil.class);

  private static final int SIZE = 2;

  /**
   * 执行创建文件
   *
   * //   * @param type 类型 示例:Dao
   *
   * @param templeteName 模板的名字 示例:BaseDao.ftl
   * @param projectPath 生成的项目路径 示例:D://create
   * @param packageName 包名 示例:com.szmirren
   * @param tableName 文件名 示例:sys_user_base
   * @param tablePrefix 前缀 示例:Dao
   * @param codeFormat 输出的字符编码格式 示例:UTF-8
   *
   * @throws Exception
   */
  public static boolean createFile(GeneratorContent content, String templeteName, String projectPath,
                                   String packageName, String module, String tableName, String tablePrefix,
                                   String codeFormat, boolean isOverride) {
    try {
      String type = gainString(templeteName.split("\\.")[0]);
      String moduleBase = StringUtils.isEmpty(module) ? "" : module + "/";
      String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/" + type.toLowerCase() + "/"
        + moduleBase;
      String classVar = StringUtil
        .toBeanPatternStr(tableName.startsWith(tablePrefix) ? tableName.substring(tablePrefix.length()) : tableName);
      String fileName;

      if (type.equalsIgnoreCase(Constant.FILE_ENTITY)) {
        fileName = StringUtil.firstCharUpperCase(classVar) + Constant.JAVA_SUFFIX;
      } else {
        fileName = StringUtil.firstCharUpperCase(classVar) + type + Constant.JAVA_SUFFIX;
      }

      if (!isOverride) {
        if (Files.exists(Paths.get(outputPath + fileName))) {
          LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
          return false;
        }
      }
      Configuration config = new Configuration(Configuration.VERSION_2_3_23);
      // 打包成jar包使用的路径
      File tempPath = Paths.get("./" + Constant.TEMPLATE_DIR_NAME + "/" + type.toLowerCase()).toFile();

      config.setDirectoryForTemplateLoading(tempPath);
      config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
      config.setDefaultEncoding("utf-8");
      Template template = null;

      template = config.getTemplate(templeteName);

      Map<String, Object> item = new HashMap<>();
      item.put("content", content);
      if (!Files.exists(Paths.get(outputPath))) {
        Files.createDirectories(Paths.get(outputPath));
      }
      try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
        template.process(item, writer);
        return true;
      } catch (TemplateException e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
        return false;
      }
    } catch (IOException e) {
      e.printStackTrace();
      LOG.error(e.getMessage());
      return false;
    }
  }

  private static String gainString(String string) {
    String[] s = string.replaceAll("[A-Z]", " $0").split(" ");
    if (s.length > SIZE) {
      return s[s.length - 1];
    }
    return "";
  }

}
